package jr.controller;

import com.google.gson.Gson;
import jr.pojo.BookInfo;
import jr.service.IBookInfoService;
import jr.service.impl.BookInfoServiceImpl;
import jr.util.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/bookinfo/*")
public class BookInfoController extends HttpServlet {

    private IBookInfoService ibfs = new BookInfoServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        int index = requestURI.lastIndexOf("/") + 1;
        String substring = requestURI.substring(index);
        if (substring.length() == 0) {
            substring = "showdt";
        }

        Class empControllerClass = this.getClass();
        Method method = null;

        try {
            method = empControllerClass.getMethod(substring, HttpServletRequest.class, HttpServletResponse.class);

            response.setContentType("application/json;charset=utf-8");
            request.setCharacterEncoding("utf-8");


            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    public void showdt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        int booktype = Integer.parseInt(request.getParameter("booktype"));
        int isborrow = Integer.parseInt(request.getParameter("bookborrow"));
        String bookname = request.getParameter("bookName");
        BookInfo bookInfo=new BookInfo();
        bookInfo.setBooktype(booktype);//-1
        bookInfo.setIsborrow(isborrow);//-1
        bookInfo.setBookname(bookname);//""

        PageHelper ph = new PageHelper();
        int ndexpage = Integer.parseInt(request.getParameter("indexpage"));
        ph.setPageIndex(ndexpage);
        if (bookInfo.getBooktype()==-1&&bookInfo.getIsborrow()==-1&&bookInfo.getBookname()==""){
            ph.setDateCount(ibfs.queryPageDateCount());
            ph.setListIndex(ibfs.queryIndexDate(ph));
        }else {
            ph.setDateCount(ibfs.queryPageDateCountLike(bookInfo));//0
            ph.setListIndex(ibfs.queryIndexDateLike(bookInfo,ph));//[]
        }


        response.getWriter().println(new Gson().toJson(ph));


    }

 }